package DAO.MysqlDAO;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import DAO.InterfaceDAO.ResultatDAO;
import Factories.FactoryMySqlDAO;
import Model.Resultat;

public class ResultatDAO_Mysql implements ResultatDAO{

	private PreparedStatement psCreate, psRead, psUpdate, psDelete, psFind, psId;//Roger ; Pour faire comme dans professeur

	public ResultatDAO_Mysql(Connection cx) {

		try {
			psCreate = cx.prepareStatement("INSERT INTO resultat SET " +
					"exercice = ?," +
					"etudiant = ?," +
					"nom = ?," +
					"note = ?," +
					"date = ?," +
			"reponse = ?");
			psRead   = cx.prepareStatement("SELECT * FROM resultat WHERE id = ?");
			psUpdate = cx.prepareStatement("UPDATE resultat SET exercice = ?," +
					" etudiant = ? ," +
					" nom = ? ," +
					" note = ? ," +
					" date = ? ," +
					" reponse = ? ," +
			"  WHERE id = ? ");
			psDelete = cx.prepareStatement("DELETE FROM resultat WHERE id = ?");
			psFind   = cx.prepareStatement("SELECT * FROM resultat");
			psId = cx.prepareStatement("SELECT id FROM resultat WHERE exercice=? AND etudiant=?"); //Roger

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean create(Resultat r) {
		try {
			psCreate.setInt(1, r.getExercice().getId());
			psCreate.setInt(2, r.getEtudiant().getIdCompte());
			psCreate.setString(3, r.getNom());
			psCreate.setDouble(4, r.getNote());
			psCreate.setDate(5, (Date) r.getDate());
			psCreate.setString(6, r.getReponses());
			psCreate.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public Resultat read(int id) {
		try {

			psRead.setInt(1, id);
			ResultSet rs = psRead.executeQuery();
			if(rs.next()){
				Resultat r = new Resultat();
				r.setId(id);
				r.setDate(rs.getDate("date"));
				r.setExercice(FactoryMySqlDAO.getInstance().createExerciceDAO().read(rs.getInt("exercice")));
				r.setNom(rs.getString("nom"));
				r.setNote(rs.getDouble("note"));
				r.setReponses(rs.getString("reponse"));
				return r;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean update(Resultat r) {
		return false;
	}

	@Override
	public boolean delete(Resultat r) {
		return false;
	}

	//Roger
	@Override
	public int id(String numExercice, String numINE) 
	{
		try {
			psId.setString(1, numExercice);
			psId.setString(2, numINE);
			ResultSet rs = psId.executeQuery();
			return rs.getInt("id");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return -1;
	}

}
